package com.example.mqttdevicesimulator.touchpad;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mqttdevicesimulator.R;
import com.example.mqttdevicesimulator.UtilConstants;
import com.example.mqttdevicesimulator.jsonformatinfo.ControlInfo;

import java.util.List;

/**
 * The adapter for device list in touch pad view.
 */
public class TDeviceAdapter extends RecyclerView.Adapter<TDeviceAdapter.ViewHolder> {

    private List<TMqttDevice> deviceList;
    private TouchPadActivity context;

    static class ViewHolder extends RecyclerView.ViewHolder {
        View recyclerView;
        ImageView mqttDeviceImage;
        TextView mqttDeviceName;
        TextView mqttDeviceStatus;

        public ViewHolder(View view) {
            super(view);
            recyclerView = view;
            mqttDeviceImage = view.findViewById(R.id.t_device_image);
            mqttDeviceName = view.findViewById(R.id.t_device_name);
            mqttDeviceStatus = view.findViewById(R.id.t_device_status);
        }
    }

    public TDeviceAdapter(List<TMqttDevice> list, TouchPadActivity context) {
        this.context = context;
        deviceList = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.t_device_item, parent,
                false);
        final ViewHolder holder = new ViewHolder(view);

        holder.recyclerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                TMqttDevice device = deviceList.get(position);
                ControlInfo controlInfo = new ControlInfo();
                controlInfo.setDevice_id(device.getDeviceId());
                if (device.getStatus().equals(UtilConstants.DeviceStatus.ON)) {
                    controlInfo.setCommand(UtilConstants.DeviceStatus.OFF);
                } else {
                    controlInfo.setCommand(UtilConstants.DeviceStatus.ON);
                }
                context.controlOtherDevice(controlInfo);
            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        TMqttDevice device = deviceList.get(position);
        holder.mqttDeviceImage.setImageResource(device.getImageId());
        holder.mqttDeviceName.setText(device.getName());
        holder.mqttDeviceStatus.setText(device.getStatus());
    }

    @Override
    public int getItemCount() {
        return deviceList.size();
    }

}
